package com.user.rabbitmq.consumer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.domain.rabbitmq.UserAvatarMQ;
import com.common.handler.ExchangeServiceHandler;
import com.common.handler.RedisKeysHandler;
import com.user.domain.pojo.UserFollow;
import com.user.domain.pojo.UserOperateLogs;
import com.user.rabbitmq.pojo.FollowerInBox;
import com.user.service.IUserFollowService;
import com.user.service.IUserOperateLogsService;
import com.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户rabbitmq消费者
 */
@Component
@Slf4j
public class UserConsumer {

    @Resource
    IUserService iUserService;

    @Resource
    IUserFollowService iUserFollowService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 更新头像信息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "user-update-avatar-queue", durable = "true", arguments = @Argument(name = "x-queue-mode", value = "lazy")), // 持久化队列 开启惰性队列
            exchange = @Exchange(name = ExchangeServiceHandler.USER_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = "user.update.avatar"
    ))
    public void updateUserAvatar(UserAvatarMQ userAvatarMQ) {
        iUserService.updateUserAvatar(userAvatarMQ.getUserId(), userAvatarMQ.getAvatarId());
        log.info("用户服务：id: {} 的用户头像更新成功", userAvatarMQ.getUserId());
    }

    /**
     * 发送给每一个粉丝的收件箱中
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "user-follow-box-queue", durable = "true", arguments = @Argument(name = "x-queue-mode", value = "lazy")), // 持久化队列 开启惰性队列
            exchange = @Exchange(name = ExchangeServiceHandler.USER_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = "user.follow.box"
    ))
    public void sendToFollowerInbox(FollowerInBox followerInBox) {
        log.info("用户服务：接收到发送给每一个粉丝的收件箱中消息");
        // 获取当前教师的所有粉丝
        Long teacherId = followerInBox.getUserId();
        List<UserFollow> list = iUserFollowService.list(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFollowUserId, teacherId));
        // 给每一个粉丝推送通知
        for (UserFollow follow : list) {
            stringRedisTemplate.opsForZSet().add(
                    RedisKeysHandler.getUserInboxKey(follow.getUserId()),
                    followerInBox.getCourseId().toString(),
                    System.currentTimeMillis());
        }
    }


}
